package com.ruoyi.system.controller.trade;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.common.BillTypeConstant;
import com.ruoyi.system.domain.db.financial.FinancialEconomic;
import com.ruoyi.system.domain.db.trade.TradeMaterialOrder;
import com.ruoyi.system.domain.vo.MaterialOrderVo;
import com.ruoyi.system.domain.vo.PageInfo;
import com.ruoyi.system.service.IFinancialEconomicService;
import com.ruoyi.system.service.ITradeMaterialOrderService;
import com.ruoyi.system.utils.MyPageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 物资交易管理Controller
 * 
 * @author ruoyi
 * @date 2023-07-31
 */
@RestController
@RequestMapping("/trade/material")
public class TradeMaterialOrderController extends BaseController
{
    @Autowired
    private ITradeMaterialOrderService tradeMaterialOrderService;

    @Autowired
    private IFinancialEconomicService financialEconomicService;

    /**
     * 查询物资交易管理列表
     */
    @PreAuthorize("@ss.hasPermi('trade:material:list')")
    @GetMapping("/list")
    public PageInfo<MaterialOrderVo> list(TradeMaterialOrder tradeMaterialOrder)
    {
        // startPage();
        List<MaterialOrderVo> list = tradeMaterialOrderService.selectTradeMaterialOrderList(tradeMaterialOrder);
        return MyPageUtils.startPage(list);
    }

    /**
     * 导出物资交易管理列表
     */
    @PreAuthorize("@ss.hasPermi('trade:material:export')")
    @Log(title = "物资交易管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TradeMaterialOrder tradeMaterialOrder)
    {
        List<MaterialOrderVo> materialOrderVos = tradeMaterialOrderService.selectTradeMaterialOrderList(tradeMaterialOrder);
        ExcelUtil<MaterialOrderVo> util = new ExcelUtil<MaterialOrderVo>(MaterialOrderVo.class);
        util.exportExcel(response, materialOrderVos, "物资交易管理数据");
    }

    /**
     * 获取物资交易管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('trade:material:query')")
    @GetMapping("")
    public AjaxResult getInfo(@RequestParam(required = false) Long orderId)
    {
        return success(tradeMaterialOrderService.selectTradeMaterialOrderByOrderId(orderId));
    }

    /**
     * 新增物资交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:material:add')")
    @Log(title = "物资交易管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TradeMaterialOrder tradeMaterialOrder)
    {
        int result = tradeMaterialOrderService.insertTradeMaterialOrder(tradeMaterialOrder);
        FinancialEconomic financialEconomic = new FinancialEconomic(
                BillTypeConstant.MATERIAL_ORDER,tradeMaterialOrder.getOrderId(),
                tradeMaterialOrder.getTotal()*(-1),tradeMaterialOrder.getRemark() // 备注从remark改过去
        );
        financialEconomicService.insertFinancialEconomic(financialEconomic);
        return toAjax(result);
    }

    /**
     * 修改物资交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:material:edit')")
    @Log(title = "物资交易管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TradeMaterialOrder tradeMaterialOrder)
    {
        boolean flag = false;
        int result = tradeMaterialOrderService.updateTradeMaterialOrder(tradeMaterialOrder);
        FinancialEconomic financialEconomic = financialEconomicService.getBillByOrderIdAndBillTypeId(tradeMaterialOrder.getOrderId(), BillTypeConstant.MATERIAL_ORDER);
        if (!financialEconomic.getSalary().equals(tradeMaterialOrder.getTotal()*(-1))) {
            financialEconomic.setSalary(tradeMaterialOrder.getTotal()*(-1));
            flag = true;
        }
        if (financialEconomic.getInfo() == null) {
            financialEconomic.setInfo("");
        }
        if (!financialEconomic.getInfo().equals(tradeMaterialOrder.getRemark())) {
            financialEconomic.setInfo(tradeMaterialOrder.getRemark());
            flag = true;
        }
        if (flag) {  // 变了就改，不然不改
            financialEconomicService.updateFinancialEconomic(financialEconomic);
        }
        return toAjax(result);
    }

    /**
     * 删除物资交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:material:remove')")
    @Log(title = "物资交易管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        List<Long> orderIdList = financialEconomicService.arrayToList(orderIds);
        List<Long> billIds = new ArrayList<>();
        for (Long orderId : orderIdList) {
            Long billId = financialEconomicService.getBillByOrderIdAndBillTypeId(orderId, BillTypeConstant.MATERIAL_ORDER).getBillId();
            billIds.add(billId);
        }
        financialEconomicService.deleteFinancialEconomicByOrderIds(billIds);
        return toAjax(tradeMaterialOrderService.deleteTradeMaterialOrderByOrderIds(orderIds));
    }
}
